package com.xm9m.web.service.api;


import com.salesmanager.core.business.customer.model.Customer;
import com.salesmanager.core.business.customer.service.CustomerAccountDetailsService;
import com.salesmanager.core.business.customer.service.CustomerService;
import com.xm9m.web.service.api.response.CustomerInfoResponse;
import com.xm9m.web.service.entity.security.SecurityCustomer;
import com.xm9m.web.service.interfaces.AbstractRestApi;
import com.xm9m.web.service.interfaces.IXm9mResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.text.NumberFormat;



public class CustomerInfoGet extends AbstractRestApi {

    private static final Logger logger = LoggerFactory.getLogger(CustomerInfoGet.class);

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CustomerAccountDetailsService customerAccountDetailsService;

    @Override
    public <T extends IXm9mResponse> T execute(String requestData, String version) throws Exception {
        CustomerInfoResponse userInfoResponse = new CustomerInfoResponse();

        Long customerId = null;
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            SecurityCustomer userDetails = (SecurityCustomer) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            customerId = userDetails.getCustomerId();
        }
        Customer customer = customerService.getById(customerId);

        if (customer != null) {
            userInfoResponse.setAlipay(customer.getAlipay());
            userInfoResponse.setNick(customer.getNick());
            userInfoResponse.setBalance(customer.getCustomerAccount().getBalance().toString());
            userInfoResponse.setId(customer.getId());
            userInfoResponse.setMobile(customer.getTelphone());
            userInfoResponse.setWxOpenId(customer.getOpenId());

            NumberFormat num = NumberFormat.getInstance();
            num.setMaximumFractionDigits(2);//最大保留两位小数
            num.setMinimumFractionDigits(2);
            return (T) userInfoResponse;
        }
        return (T) userInfoResponse;
    }
}